package com.icss.servlets;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;

import com.icss.beans.FileVO;
import com.icss.beans.User;
import com.icss.daos.FileCenterDao;

import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;

public class FileCenterServlet extends HttpServlet {

	private String webTempPath;

	public void init() {
	  webTempPath = getServletContext().getRealPath("/") + "upload";
	}
	
	public FileCenterServlet() {
		super();
	}

	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request,response);
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		FileCenterDao fileDao = new FileCenterDao();
		String action = request.getParameter("action");
		HttpSession session = request.getSession();
		User u = (User)session.getAttribute("User");
		int parentID = 0;
		
		int fID = 0;
		if("showDir".equals(action)){
			
				fID = Integer.parseInt(request.getParameter("parentID"));
				HttpSession s = request.getSession();
				s.setAttribute("fileID", fID);
				
				ArrayList<FileVO> fileDIR = fileDao.getFilesDIR(u.getUid(), fID);	
				
				request.setAttribute("fileDIRlist", fileDIR);
				request.setAttribute("signStr", "p");
				request.getRequestDispatcher("/page/table_files/index_files/left.jsp").forward(request, response);
			
			
		}else if("folder".equals(action)){
			
				fID = Integer.parseInt(request.getParameter("parentID"));				
				String fName = fileDao.GetParentName(fID);
				int isShare = fileDao.IsShare(fID);
				String share="";
				if(isShare==0){
					share="y";
				}else{
					share="n";
				}
				
				request.setAttribute("isShare", share);
				request.setAttribute("fName", fName);
				ArrayList<FileVO> file = fileDao.getFiles(u.getUid(), fID);	
				String sign = "no";
				if(file.size()==0){
					sign="no";
				}else{
					
					sign="yes";
					request.setAttribute("filelist", file);
				}
				

				request.setAttribute("sign", sign);
				request.setAttribute("parentID", fID);
			
			request.getRequestDispatcher("/page/table_files/index_files/folder.jsp").forward(request, response);
		}else if("newFile".equals(action)){

			int parentId = Integer.parseInt(request.getParameter("parentID"));
			String URL = fileDao.GetParentName(parentId);
		     request.setCharacterEncoding("utf-8");
		     response.setCharacterEncoding("utf-8");
		     String DirURL="";
		     String fileURL="";
		     if(URL.equals("根目录")){
		    	 DirURL = webTempPath+"\\"+u.getUserName()+"\\";
		    	 fileURL="upload\\"+u.getUserName();
		     }else{
		    	 DirURL = webTempPath+"\\"+u.getUserName()+"\\"+URL+"\\";
		    	 fileURL="upload\\"+u.getUserName()+"\\"+URL+"\\";
		     }
		     
			String fURL = fileDao.ChangeURL(DirURL);
			File fileDir = new File(fURL);
			
			boolean t =fileDir.mkdir();
			System.out.println(t);
			
			 MultipartRequest mpr = new MultipartRequest(request, DirURL, 1024*1024*1024,"utf-8", new DefaultFileRenamePolicy());
			 Enumeration params = mpr.getFileNames();
			String fileName = mpr.getParameter("fileName");
			String remark = mpr.getParameter("fileContext");
			long filesize = 0;
			String FName = "";
			
			
			for (int i = 1; params.hasMoreElements(); i++){
				
				 String src=new String(mpr.getFilesystemName((String)params.nextElement()));
				 File file=new File(DirURL+"\\"+src);
				 filesize = file.length()/1024;
				 FName = src;				
			}
			fileURL = fileURL+FName;
//			System.out.println("The file size:"+filesize);
//			System.out.println("The file Name:"+FName);
//			System.out.println("The file URL:"+fileURL);

			FileVO file = new FileVO();
	
			file.setFileName(fileName);
			file.setFileSize((int)filesize);
			file.setFileURL(fileURL);
			file.setParentID(parentId);
			file.setRemark(remark);
			file.setUid(u.getUid());
			file.setIsFile(1);
			
			if(fileDao.uploadFile(file)){
				request.getRequestDispatcher("FileCenterServlet?action=folder&parentID="+parentId).forward(request, response);
			}
		}else if("newFileDIR".equals(action)){
			HttpSession ses= request.getSession();
			int parentId = Integer.parseInt(ses.getAttribute("fileID").toString());
			String fileName = request.getParameter("fileName");
			String 	fileURL = "upload\\"+u.getUserName()+"\\";
			
			FileVO file = new FileVO();
			file.setParentID(parentId);
			file.setFileName(fileName);
			file.setFileURL(fileURL);
			file.setUid(u.getUid());
			
			System.out.println(webTempPath+"\\"+u.getUserName()+"\\"+fileName);
			String dirUrl = webTempPath+"\\"+u.getUserName()+"\\"+fileName;
			
			int fid = fileDao.CreateFileDIR(file,fileDao.ChangeURL(dirUrl));
			//response.setHeader("refresh", "3;url=FileCenterServlet?action=showDir&parentID="+parentId);
			request.getRequestDispatcher("FileCenterServlet?action=folder&parentID="+fid).forward(request, response);
		}else if("toFileDIR".equals(action)){
			int parentId = Integer.parseInt(request.getParameter("parentID"));

	
			request.getRequestDispatcher("/page/table_files/index_files/newFileDIR.jsp").forward(request, response);
		}else if("toNewFile".equals(action)){
			int parentId = Integer.parseInt(request.getParameter("parentID"));
		
			request.setAttribute("parentId", parentId);
	
			request.getRequestDispatcher("/page/table_files/index_files/newFile.jsp").forward(request, response);
		}else if("displayFile".equals(action)){
			int fileID = Integer.parseInt(request.getParameter("fileID"));
			FileVO file = fileDao.GetFile(fileID);
			String[] fileName = file.getFileURL().split("\\\\");
//			file.setFileURL(getServletContext().getRealPath("/")+file.getFileURL());
//			System.out.println(getServletContext().getRealPath("/")+file.getFileURL());
			request.setAttribute("fName", fileName[fileName.length-1]);
			request.setAttribute("fileID", fileID);
			request.setAttribute("file", file);
			request.getRequestDispatcher("/page/table_files/index_files/showFile.jsp").forward(request, response);
		}else if("editFile".equals(action)){
			int fileID = Integer.parseInt(request.getParameter("fileID"));
			FileVO file = fileDao.GetFile(fileID);
			String[] fileName = file.getFileURL().split("\\\\");
			request.setAttribute("fName", fileName[fileName.length-1]);
			
			System.out.println(fileName[fileName.length-1]);
			request.setAttribute("file", file);
			request.getRequestDispatcher("/page/table_files/index_files/editFile.jsp").forward(request, response);
		}else if("updatefile".equals(action)){
			
			int fileID = Integer.parseInt(request.getParameter("fileID"));
			String fileURL2 = fileDao.GetFileURL(fileID);			
			int last = fileURL2.lastIndexOf("\\");	
			String fileURL = fileURL2.substring(0, last);
			String DirURL=getServletContext().getRealPath("/")+fileURL;
			MultipartRequest mpr = new MultipartRequest(request, DirURL, 1024*1024*1024,"utf-8", new DefaultFileRenamePolicy());
			 
			String fileName = mpr.getParameter("fileName");
			String remark = mpr.getParameter("fileContext");
			String txt = mpr.getParameter("txt");			

			int id = fileDao.GetParentID(fileID);
			FileVO vo = new FileVO();
			vo.setFileID(fileID);
			vo.setFileName(fileName);
			vo.setRemark(remark);
			if(txt.equals("")){				
				fileDao.updateFile(vo);
			}else{
				Enumeration params = mpr.getFileNames();				
				String src=new String(mpr.getFilesystemName((String)params.nextElement()));
				vo.setFileURL(fileURL+"\\"+src);
				fileDao.updateFile2(vo,getServletContext().getRealPath("/"));
			}
		
			
			request.getRequestDispatcher("FileCenterServlet?action=editFile&fileID="+fileID).forward(request, response);
		}else if("shareFile".equals(action)){
			int fileID = Integer.parseInt(request.getParameter("parentID"));
			if(fileDao.ShareFile(fileID)){
				request.getRequestDispatcher("FileCenterServlet?action=folder&parentID="+fileID).forward(request, response);
			}
		}else if("UnShareFile".equals(action)){
			int fileID = Integer.parseInt(request.getParameter("parentID"));
			if(fileDao.UnShareFile(fileID)){
				request.getRequestDispatcher("FileCenterServlet?action=folder&parentID="+fileID).forward(request, response);
			}
		}else if("showShareFile".equals(action)){
			
			ArrayList<FileVO> fileList = fileDao.getShareFilesDIR();
			request.setAttribute("fileList", fileList);
			
			request.getRequestDispatcher("/page/table_files/index_files/ShareFile.jsp").forward(request, response);
		}else if("showPersonFile".equals(action)){
			int id = fileDao.getDIRFileID(u.getUid(),0);
			request.setAttribute("fID",""+id);
		
			request.getRequestDispatcher("/page/table_files/files.jsp").forward(request, response);
		}else if("display".equals(action)){
			int fileID = Integer.parseInt(request.getParameter("fileID"));
			FileVO file = fileDao.GetFile(fileID);
			if(file==null){
				request.setAttribute("isempty", "y");
			}else{
				request.setAttribute("isempty", "n");
				String[] fileName = file.getFileURL().split("\\\\");
				request.setAttribute("fName", fileName[fileName.length-1]);
				request.setAttribute("fileID", fileID);
				request.setAttribute("file", file);
			}
			
			request.getRequestDispatcher("/page/table_files/index_files/displayShareFile.jsp").forward(request, response);
		}else if("displayShareFile2".equals(action)){
			int fileID = Integer.parseInt(request.getParameter("fileID"));
			ArrayList<FileVO> filelist = fileDao.GetChildFiles(fileID);
			String fileName = fileDao.GetParentName(fileID);
			if(filelist.size()==0){
				request.setAttribute("isempty", "y");
				request.setAttribute("fName", fileName);
			}else{
				request.setAttribute("isempty", "n");
				request.setAttribute("fName", fileName);
				request.setAttribute("file", filelist);
			}
			
			request.getRequestDispatcher("/page/table_files/index_files/displayFiles.jsp").forward(request, response);
		}else if("delFile".equals(action)){
			int fileID = Integer.parseInt(request.getParameter("fileID"));
			int id = fileDao.GetParentID(fileID);
			fileDao.delFile(fileID, getServletContext().getRealPath("/"));
			request.getRequestDispatcher("FileCenterServlet?action=folder&parentID="+id).forward(request, response);
		}else if("deleteAll".equals(action)){
			String fileIDList = request.getParameter("auidList");
			int pid = Integer.parseInt(request.getParameter("pid"));
			int id = fileDao.GetParentID(pid);
			fileDao.delAllFile(fileIDList, getServletContext().getRealPath("/"));
			request.getRequestDispatcher("FileCenterServlet?action=folder&parentID="+id).forward(request, response);
		}else if("delShareFileDIR".equals(action)){
			int fileID = Integer.parseInt(request.getParameter("fileID"));
			fileDao.delShareFileDIR(fileID,getServletContext().getRealPath("/"));
			request.getRequestDispatcher("FileCenterServlet?action=showShareFile").forward(request, response);
		}else if("findNewsFile".equals(action)){
			System.out.println("fdsfs");
			List<FileVO> fvo = fileDao.getNewFiles(u.getUid());
			
			PrintWriter out = response.getWriter();
			JSONArray json = JSONArray.fromObject(fvo);
			out.print(json);
			
		}
		fileDao.close();
		
		
	}

	

}
